/**
 * 240. 搜索二维矩阵 II
 */
public class Solution_240 {
    /**
     * 从矩阵左下角或者右上角出发，每次削去一行或一列
     * <p>
     * 时间复杂度：O(M+N)
     * <p>
     * 空间复杂度：O(1)
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length, col = matrix[0].length;
        // 从矩阵左下角出发
        int i = row - 1, j = 0;
        while (i >= 0 && j < col) {
            if (matrix[i][j] > target) {
                i--;
            } else if (matrix[i][j] < target) {
                j++;
            } else {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Solution_240 solution = new Solution_240();
        int[][] matrix = { 
            { 1, 4, 7, 11, 15 }, 
            { 2, 5, 8, 12, 19 }, 
            { 3, 6, 9, 16, 22 }, 
            { 10, 13, 14, 17, 24 },
            { 18, 21, 23, 26, 30 } 
        };
        int target = 5;
        boolean ans = solution.searchMatrix(matrix, target);
        System.out.println(ans);
        target = 20;
        ans = solution.searchMatrix(matrix, target);
        System.out.println(ans);
    }
}
